package com.mf.morefun.base;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.mf.morefun.R;
import com.mf.morefun.widget.StatusBarUtil;
import com.umeng.analytics.MobclickAgent;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.SystemBarTintManager;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import butterknife.ButterKnife;


/**
 * ProjectName：wisdomtransit
 * PackageName：com.zhcx.wisdomtransit.wisdomtransit.base
 * description:基类
 * Date：2016/9/5 9:33
 * Author：Steven
 * ClassName:BaseBusActivity
 **/
public abstract class BaseBusActivity extends AppCompatActivity {
    protected Context mContext;
    private static final int COLOR_DEFAULT = Color.parseColor("#20000000");
    private SPUtils mSPutils;
    private int FLAG_HOMEKEY_DISPATCHED = 0x80000000; //需要自己定义标志

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(this.getContentLayoutId());
        setStatusBar(getNaviteColor());
        ButterKnife.bind(this);
        AppManager.getAppManager().addActivity(this);
        DeviceUtils.hideNavigationBar(this);
        mSPutils = new SPUtils(this);
        mContext = this;
        this.initView(savedInstanceState);
        this.initData();
    }

    /**
     * 设置状态栏颜色
     */
    protected void setStatusBar(int color) {
//        if (color == 0) {
//            StatusBarUtil.setColor(this, this.getResources().getColor(R.color.white), 50);
//        } else if (color == 1) {
//            StatusBarUtil.setColor(this, this.getResources().getColor(R.color.blue_caryards), 0);
//        }else if (color == 2) {
//            StatusBarUtil.setColor(this, this.getResources().getColor(R.color.white), 0);
//        }else if(color == 3){
            StatusBarUtil.setTranslucentForCoordinatorLayout(this, 0);
//        } else {
//            StatusBarUtil.setColor(this, this.getResources().getColor(color), 50);
//        }
    }

    public void resetFragmentView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            View contentView = findViewById(android.R.id.content);
            if (contentView != null) {
                ViewGroup rootView;
                rootView = (ViewGroup) ((ViewGroup) contentView).getChildAt(0);
                if (rootView.getPaddingTop() != 0) {
                    rootView.setPadding(0, 0, 0, 0);
                }
                View statusBarView = new View(this);
                ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        getStatusBarHeight(this));
                statusBarView.setBackgroundColor(COLOR_DEFAULT);
                rootView.addView(statusBarView, lp);
            }
        }
    }


    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 设置导航栏颜色
     *
     * @param color
     */
    public void setNaviteColor(int color) {
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        if (color > 0) {
            tintManager.setStatusBarTintResource(color);
        } else {
            tintManager.setStatusBarTintResource(R.color.white);
        }
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            AppManager.getAppManager().removeActivity(this);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 设置主页面颜色
     */
    protected abstract int getNaviteColor();

    /**
     * 加载页面布局文件
     */
    protected abstract int getContentLayoutId();

    /**
     * 页面控件初始化
     */
    protected abstract void initView(Bundle savedInstanceState);

    /**
     * Initialize the Activity data
     */
    protected abstract void initData();

    /**
     * Toast
     *
     * @param msg
     */
    public void showToast(String msg) {
        this.showToast(msg, Toast.LENGTH_SHORT);
    }

    public void showToast(String msg, int duration) {
        if (msg == null) return;
        if (duration == Toast.LENGTH_SHORT || duration == Toast.LENGTH_LONG) {
            ToastUtils.show(this, msg, duration);
        } else {
            ToastUtils.show(this, msg, ToastUtils.LENGTH_SHORT);
        }
    }

    public void showToast(int resId) {
        this.showToast(resId, Toast.LENGTH_SHORT);
    }


    public void showToast(int resId, int duration) {
        if (duration == Toast.LENGTH_SHORT || duration == Toast.LENGTH_LONG) {
            ToastUtils.show(this, resId, duration);
        } else {
            ToastUtils.show(this, resId, ToastUtils.LENGTH_SHORT);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *l
     * @param token。
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
